package org.ccay.core.exception.impl;

import java.text.MessageFormat;
import java.util.Collection;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;

import javax.inject.Named;

import org.ccay.core.exception.ApplicationException;
import org.ccay.core.exception.ExceptionHandler;
import org.ccay.core.ioc.Ccay;
import org.ccay.core.server.IAfterStartupHandler;
import org.ccay.core.server.StartupEventArgs;
import org.ccay.core.util.StringUtil;


/**
 * 异常信息管理器
 * 
 * 
 * @since 2013-4-22
 */
@Named
public class ExceptionMessageManager implements IAfterStartupHandler{
	
	/**
	 * 异常配置信息
	 */
	private static final Map<String, ExceptionConfigBean> exceptionConfigs = new ConcurrentHashMap<String, ExceptionConfigBean>();
	
	/**
	 * 国际化信息
	 */ 
	private static ResourceBundle resourceBundle;
	
	/** 
	 * 构建异常配置
	 * @param configs
	 */
	public static void buildConfigs(Collection<ExceptionConfigBean> configs){
		for(ExceptionConfigBean ecb : configs){
			exceptionConfigs.put(ecb.getErrorCode(),ecb); 
		}
	}
	
	/** 
	 * 构建异常配置
	 * @param configs
	 */
	public static void buildConfig(ExceptionConfigBean config){
			exceptionConfigs.put(config.getErrorCode(), config); 
	}
	
	/** 
	 * 获取异常信息
	 * @param errorCode
	 * @return
	 */
	public static String getMessage(String errorCode){
		if(StringUtil.isNullOrEmpty(errorCode)){
			return ExceptionHandler.MISSED_MESSAGE + "empty error code.";
		}
		
		String msg  = null;
		
		if (resourceBundle != null) {
			// 首先从国际化中获取异常信息
			msg = resourceBundle.getString(errorCode);
		}
		
		if (!StringUtil.isNullOrEmpty(msg)) {
			return msg;
		}
		
		//从配置文件中获取异常信息
		ExceptionConfigBean ecb = exceptionConfigs.get(errorCode);
		if(ecb != null){
			return ecb.getExceptionMessage();
		}
		
		return ExceptionHandler.MISSED_MESSAGE+errorCode ;
	}
	
	/** 
	 * 获取异常信息
	 * @param errorCode
	 * @param args
	 * @return
	 */
	public static String getMessage(String errorCode,Object... args){
		if(args == null || args.length ==0){
			return getMessage(errorCode);
		}
		
		return MessageFormat.format(getMessage(errorCode),args);
	}
	
	/** 
	 * 获取系统异常的错误信息
	 * @return
	 */
	public static String getSystemErrorMessage(){
		return getMessage("ccay.core.99998888", 
				Thread.currentThread().getName().replaceFirst("WebContainer : ",StringUtil.EMPTY));
	}

	public void execute(Object sender, StartupEventArgs args) throws ApplicationException {
		resourceBundle = Ccay.getContext().getBean("i18nResourceBundle", ResourceBundle.class);
	}

	public int getOrder() {
		return 20;
	}
}
